const fs = require("fs");
const path = require("path");

const publicDir = "./public";
const distDir = "./dist";

if (fs.existsSync(distDir)) {
  fs.rmSync(distDir, { recursive: true, force: true });
}

fs.mkdirSync(distDir);

let htmlTemplate = fs.readFileSync("./index.html").toString();

let build = (src, dst) => {
  fs.readdir(src, (err, files) => {
    if (err) {
      throw err;
    }

    files.forEach((file) => {
      let srcFile = path.join(src, file);
      let dstFile = path.join(dst, file);

      fs.stat(srcFile, (err, stats) => {
        if (err) {
          throw err;
        }
        if (stats.isDirectory()) {
          fs.mkdir(dstFile, () => {
            build(srcFile, dstFile);
          });
        } else {
          fs.copyFileSync(srcFile, dstFile);
        }
      });
    });

    if (!(files.includes("index.html") || files.includes("index.md"))) {
      let indexFile = path.join(dst, "index.html");
      let title = path.relative(distDir, dst).replace("\\", "/");

      let htmlText = htmlTemplate
        .replace("#title#", title)
        .replace(
          "#list#",
          files
            .map((file) => `<li><a href='./${file}'>${file}</a></li>`)
            .join("")
        );
      fs.writeFileSync(indexFile, htmlText);
    }
  });
};

build(publicDir, distDir);
